package com.base.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.sys.dto.SysDictQueryDTO;
import com.base.sys.entity.SysDict;
import com.base.sys.service.ISysDictService;
import com.base.util.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gjj
 * @since 2018-11-30
 */
@RestController
@RequestMapping("/sys/sys-dict")
public class SysDictController {


    @Autowired
    private ISysDictService sysDictService;


    @RequestMapping("/get-types")
    public Result getTypes(){
        QueryWrapper<SysDict> queryWrapper=new QueryWrapper<SysDict>();
        queryWrapper.groupBy("TYPE","DESCRIPTION");
        queryWrapper.excludeColumns(SysDict.class,"ID","NAME",
                "VALUE","VERSION","CREATE_TIME","UPDATE_TIME");
        List<SysDict> list = sysDictService.list(queryWrapper);
        return Result.successResult(list);
    }


    @RequestMapping("/list")
    @RequiresPermissions("dict:query")
    public Result list(@RequestBody SysDictQueryDTO sysDictQueryDTO){
        Integer page = sysDictQueryDTO.getPage();
        Integer limit = sysDictQueryDTO.getLimit();
        QueryWrapper<SysDict> queryWrapper=new QueryWrapper<SysDict>();
        String type = sysDictQueryDTO.getType();
        queryWrapper.orderByAsc("TYPE","VALUE");
        if(!StringUtils.isEmpty(type)){
            queryWrapper.eq("TYPE",type);
        }
        if(page==null&&limit==null){
            List<SysDict> list = sysDictService.list(queryWrapper);
            return Result.successResult(list);
        }
        Page<SysDict> pageRequest=new Page<SysDict>(page,limit);
        IPage<SysDict> sysDictIPage = sysDictService.page(pageRequest, queryWrapper);
        return Result.successResult(sysDictIPage);
    }


    @RequestMapping("/save-or-update")
    @RequiresPermissions("dict:edit")
    public Result saveOrUpdate(@RequestBody SysDict sysDict){
        String id = sysDict.getId();
        if(StringUtils.isEmpty(id)){
            sysDict.setVersion(1);
            sysDict.setCreateTime(new Date());
        }else{
            sysDict.setUpdateTime(new Date());
        }
        boolean b = sysDictService.saveOrUpdate(sysDict);
        if(!b){
            throw new RuntimeException();
        }
        return Result.successResult();
    }




}
